<!--
  上传文件组件
-->
<template>
  <div aria-label="上传文件">
    <button type="button" v-on:click="selectFile()" class="btn btn-white btn-warning btn-round">
      <i class="ace-icon fa fa-upload bigger-120 blue"></i>
      {{ text }}
    </button>
    <input class="hidden" type="file" ref="file" v-on:change="uploadFile()" v-bind:id="inputId+'-input'"/>
  </div>
</template>

<script>
export default {
  name: 'big-file',
  props: {
    //子---父传值
    text: {
      default: "上传大文件",
    },
    inputId: {
      default: "file-upload",
    },
    suffixs: {
      default: [],
    },
    //回调函数
    afterUpload: {
      type: Function,
      default: null
    },
    //文件用途
    use:{
      default:""
    },
  },
  data: function () {
    return {}
  },
  methods: {
    /**上传大文件*/
    uploadFile() {
      let _this = this;
      // let formData = new window.FormData();
      let file = _this.$refs.file.files[0];

      //判断文件上传格式
      let suffixs = _this.suffixs;
      let fileName = file.name;
      let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
      let validateSuffix = false;
      for (let i = 0; i < suffixs.length; i++) {
        if (suffixs[i].toLowerCase() === suffix) {
          validateSuffix = true;
          break;
        }
      }
      if (!validateSuffix) {
        toast.warning("文件格式不正确！只支持上传" + suffixs.join("、"));
        $('#' + _this.inputId + "-input").val("");
        return;
      }

      /**分片上传*/
      //1.文件分片
      let shardSize = 10 * 1024 *1024; //10MB为一个分片
      let shardIndex = 1; //分片索引

      let size = file.size; //文件大小
      let shardTotal = Math.ceil(size/shardSize);  //总片数

      let key = hex_md5(file.name + file.size + file.type);  //加密文件标识
      let key10 = parseInt(key,16);  //10进制
      let key62 = Tool._10to62(key10);  //62进制  26大学字母+26小写字母+10阿拉伯数字
      // console.log(key,key10,key62);

      let param = {
        'shardIndex': shardIndex,
        'shardSize': shardSize,
        'shardTotal': shardTotal,
        'use':_this.use,
        'name':file.name,
        'suffix':suffix,
        'size':file.size,
        'key':key62,
      }
      _this.check(param);


    },
    /**检查文件状态，是否已经上传，上传到第几个分片*/
    check:function (param){
      let _this = this;
      _this.$ajax.get(process.env.VUE_APP_SERVER + '/file/admin/check/' + param.key).then((response)=>{
        let resp = response.data;
        if(resp.success){
          let obj = resp.content;
          if(!obj){
            param.shardIndex = 1;
            console.log("没有找到文件记录，从分片1开始上传！");
            _this.upload(param);
          }else if(obj.shardIndex === obj.shardTotal) {
            toast.success("文件急速妙传成功！")
            _this.afterUpload(resp);
            $('#' + _this.inputId + "-input").val("");
          }else {
            param.shardIndex = obj.shardIndex + 1;
            console.log("找到文件记录，从分片" + param.shardIndex + "开始上传！");
            _this.upload(param);
          }
        } else {
          toast.warning("文件上传失败！")
          $('#' + _this.inputId + "-input").val("");
        }
      });
    },

    /**将图片转为base64传输*/
    upload: function (param) {
      //将图片转为base64传输
      let _this = this;
      let fileReader = new FileReader();
      let shardIndex = param.shardIndex;
      let shardTotal = param.shardTotal;
      let shardSize = param.shardSize;
      let fileShard = _this.getFileShard(shardIndex, shardSize);
      //显示进度条
      Progress.show(parseInt((shardIndex - 1)*100 / shardTotal));

      fileReader.onload = function (e) {
        let base64 = e.target.result;
        // console.log("base64:",base64);
        param.shard = base64;

        _this.$ajax.post(process.env.VUE_APP_SERVER + '/file/admin/upload', param).then((response) => {

          let resp = response.data;
          console.log("上传文件成功：", resp);
          //修改进度条数据
          Progress.show(parseInt(shardIndex*100/shardTotal));
          if (shardIndex < shardTotal) {
            //上传下一个分片
            param.shardIndex = param.shardIndex+1;
            _this.upload(param);
          } else {
            Progress.hide();
            _this.afterUpload(resp);
            $('#' + _this.inputId + "-input").val("");
          }



        });
      };
      fileReader.readAsDataURL(fileShard);
    },

    /**点击上传按钮，触发上传事件*/
    selectFile() {
      let _this = this;
      $('#' + _this.inputId + "-input").trigger("click");
    },
    /**获取FileShard */
    getFileShard: function (shardIndex, shardSize) {
      let _this = this;
      let file = _this.$refs.file.files[0];
      let start = (shardIndex - 1) * shardSize; //当前分片的索引位置
      // let end = start + shardSize;  //当前分片的结束位置
      let end = Math.min(file.size, start + shardSize);  //当前分片的结束位置

      let fileShard = file.slice(start, end); //从文件中截取当前的分片数据
      return fileShard;
    },
  }
}
</script>

<style scoped>
</style>